package org.apache.database.result;

import org.apache.database.utils.AnnotationUtil;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ResultHandler {
    public <T>List<T> forList(Class<T> tClass, ResultSet resultSet) throws SQLException, IllegalAccessException {
        List<T> result =new ArrayList<>();
        try {
            while (resultSet.next()){
                /**
                 * 实例化tClass
                 */
                T item = newInstance(tClass);
                /**
                 * 获取所有字段，对所有字段设置这一行的记录
                 */
                Field[] declaredFields = tClass.getDeclaredFields();
                for (int i = 0; i < declaredFields.length; i++) {
                    Field itemField = declaredFields[i];

                    itemField.setAccessible(true);
                    Object data = resultSet.getObject(AnnotationUtil.getColumnName(itemField), itemField.getType());

                    itemField.set(item,data);
                }
                result.add(item);
            }
        }finally {
            resultSet.getStatement().close();
            resultSet.close();
        }
        return result;
    }

    public <T> int forType(Class<T> tClass, ResultSet resultSet){
        try {
            while (resultSet.next()){
                    return resultSet.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                resultSet.getStatement().close();
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
        return 0;
    }
    private  <T> T newInstance(Class<T> tClass){
        try {
            return tClass.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}
